package com.warom.sdg.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.os.AsyncTask;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 * 害虫检测辅助类
 * 用于处理害虫检测相关的功能，包括图像处理、标注等
 */
public class PestDetectionHelper {
    private static final String TAG = "PestDetectionHelper";
    
    // 线程池，用于异步加载图片
    private static final Executor executor = Executors.newFixedThreadPool(2);
    
    /**
     * 害虫检测结果
     */
    public static class PestDetectionResult {
        // 害虫类型ID
        public int pestTypeId;
        
        // 害虫类型名称
        public String pestTypeName;
        
        // 置信度 (0.0-1.0)
        public float confidence;
        
        // 检测框位置 (左上角x, 左上角y, 右下角x, 右下角y)
        public RectF boundingBox;
        
        public PestDetectionResult(int pestTypeId, String pestTypeName, float confidence, RectF boundingBox) {
            this.pestTypeId = pestTypeId;
            this.pestTypeName = pestTypeName;
            this.confidence = confidence;
            this.boundingBox = boundingBox;
        }
    }
    
    /**
     * 图像加载回调接口
     */
    public interface ImageLoadCallback {
        void onImageLoaded(Bitmap bitmap);
        void onImageLoadFailed(Exception e);
    }
    
    /**
     * 标注图像加载回调接口
     */
    public interface AnnotatedImageLoadCallback {
        void onAnnotatedImageLoaded(Bitmap bitmap, List<PestDetectionResult> results);
        void onImageLoadFailed(Exception e);
    }
    
    /**
     * 从URL异步加载图片
     * @param imageUrl 图片URL
     * @param callback 加载回调
     */
    public static void loadImageAsync(final String imageUrl, final ImageLoadCallback callback) {
        executor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    Bitmap bitmap = loadImageFromUrl(imageUrl);
                    callback.onImageLoaded(bitmap);
                } catch (Exception e) {
                    Log.e(TAG, "加载图像失败: " + e.getMessage(), e);
                    callback.onImageLoadFailed(e);
                }
            }
        });
    }
    
    /**
     * 从URL加载图片
     * @param imageUrl 图片URL
     * @return 位图对象
     * @throws IOException 加载异常
     */
    public static Bitmap loadImageFromUrl(String imageUrl) throws IOException {
        URL url = new URL(imageUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream inputStream = connection.getInputStream();
        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
        inputStream.close();
        connection.disconnect();
        return bitmap;
    }
    
    /**
     * 解析害虫检测结果
     * @param pests 害虫检测原始数据
     * @return 解析后的害虫检测结果列表
     */
    public static List<PestDetectionResult> parsePestDetectionResults(String[][] pests) {
        if (pests == null || pests.length == 0) {
            return new ArrayList<>();
        }
        
        List<PestDetectionResult> results = new ArrayList<>();
        
        for (String[] pest : pests) {
            if (pest.length >= 6) {
                try {
                    // 解析坐标和类型数据
                    float x1 = Float.parseFloat(pest[0]);
                    float y1 = Float.parseFloat(pest[1]);
                    float x2 = Float.parseFloat(pest[2]);
                    float y2 = Float.parseFloat(pest[3]);
                    float confidence = Float.parseFloat(pest[4]);
                    int pestTypeId = Integer.parseInt(pest[5]);
                    
                    // 获取害虫类型名称
                    String pestTypeName = OpenApiClient.PestType.getName(pestTypeId);
                    
                    // 创建检测框
                    RectF boundingBox = new RectF(x1, y1, x2, y2);
                    
                    // 添加到结果列表
                    results.add(new PestDetectionResult(pestTypeId, pestTypeName, confidence, boundingBox));
                } catch (NumberFormatException e) {
                    Log.e(TAG, "解析害虫数据失败: " + e.getMessage(), e);
                }
            }
        }
        
        return results;
    }
    
    /**
     * 在图像上标注害虫检测结果
     * @param originalBitmap 原始图像
     * @param results 害虫检测结果列表
     * @return 标注后的图像
     */
    public static Bitmap annotateImage(Bitmap originalBitmap, List<PestDetectionResult> results) {
        if (originalBitmap == null) {
            return null;
        }
        
        // 创建可变位图，支持绘制
        Bitmap annotatedBitmap = originalBitmap.copy(Bitmap.Config.ARGB_8888, true);
        Canvas canvas = new Canvas(annotatedBitmap);
        
        // 创建画笔
        Paint boundingBoxPaint = new Paint();
        boundingBoxPaint.setStyle(Paint.Style.STROKE);
        boundingBoxPaint.setStrokeWidth(5f);
        boundingBoxPaint.setColor(Color.RED);
        
        Paint textPaint = new Paint();
        textPaint.setColor(Color.WHITE);
        textPaint.setTextSize(36f);
        textPaint.setFakeBoldText(true);
        
        Paint bgPaint = new Paint();
        bgPaint.setColor(Color.RED);
        bgPaint.setAlpha(160);
        bgPaint.setStyle(Paint.Style.FILL);
        
        // 绘制检测框和标签
        for (PestDetectionResult result : results) {
            // 绘制检测框
            canvas.drawRect(result.boundingBox, boundingBoxPaint);
            
            // 准备标签文本
            String label = result.pestTypeName + " " + String.format("%.1f%%", result.confidence * 100);
            
            // 测量文字宽度
            float textWidth = textPaint.measureText(label);
            float textHeight = 36f;
            
            // 绘制标签背景
            float textLeft = result.boundingBox.left;
            float textTop = result.boundingBox.top - textHeight - 5;
            if (textTop < 0) textTop = result.boundingBox.top + 5;
            
            canvas.drawRect(
                    textLeft, 
                    textTop, 
                    textLeft + textWidth + 10, 
                    textTop + textHeight, 
                    bgPaint);
            
            // 绘制标签文字
            canvas.drawText(label, textLeft + 5, textTop + 28, textPaint);
        }
        
        return annotatedBitmap;
    }
    
    /**
     * 从URL加载图片，并标注害虫检测结果
     * @param imageUrl 图片URL
     * @param pests 害虫检测原始数据
     * @param callback 回调接口
     */
    public static void loadAndAnnotateImageAsync(final String imageUrl, final String[][] pests, 
                                               final AnnotatedImageLoadCallback callback) {
        executor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    // 加载图像
                    Bitmap originalBitmap = loadImageFromUrl(imageUrl);
                    
                    // 解析害虫检测结果
                    List<PestDetectionResult> results = parsePestDetectionResults(pests);
                    
                    // 标注图像
                    Bitmap annotatedBitmap = annotateImage(originalBitmap, results);
                    
                    // 回调结果
                    callback.onAnnotatedImageLoaded(annotatedBitmap, results);
                    
                } catch (Exception e) {
                    Log.e(TAG, "加载和标注图像失败: " + e.getMessage(), e);
                    callback.onImageLoadFailed(e);
                }
            }
        });
    }
    
    /**
     * 处理截图结果
     * @param result 截图API返回的结果
     * @param callback 回调接口
     */
    public static void processScreenshotResult(final OpenApiClient.ScreenshotResult result,
                                            final AnnotatedImageLoadCallback callback) {
        if (result == null || result.image == null || result.image.isEmpty()) {
            callback.onImageLoadFailed(new IllegalArgumentException("截图结果为空"));
            return;
        }
        
        loadAndAnnotateImageAsync(result.image, result.pests, callback);
    }
} 